package com.itheima.service.impl;

import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.OrderSettingDTO;
import com.itheima.service.OrderSettingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class OrderSettingServiceImpl implements OrderSettingService {
    private final OrderSettingMapper orderSettingMapper;

    @Override
    public List<OrderSetting> getOrderSettingByMonth(String month) {
        return orderSettingMapper.getOrderSettingByMonth(month);
    }

    @Override
    public void editNumberByOrderDate(OrderSettingDTO orderSettingDTO) {
        orderSettingMapper.editNumberByOrderDate(orderSettingDTO);
    }

    @Override
    public void download(String filename, HttpServletResponse response) {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/ordersetting_template.xlsx");
        if (in == null) {
            log.error("模板文件不存在");
            return;
        }
        try (XSSFWorkbook excel = new XSSFWorkbook(in);
             ServletOutputStream out = response.getOutputStream()) {
            excel.write(out);
            out.flush();
        } catch (IOException e) {
            log.error("文件下载失败", e);
        }
    }

    @Override
    public void importExcelData(MultipartFile excelFile) throws IOException {
            // 1. 创建工作簿对象
            Workbook workbook;
            if (excelFile.getOriginalFilename().endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(excelFile.getInputStream());
            } else {
                workbook = new HSSFWorkbook(excelFile.getInputStream());
            }

            // 2. 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();

            // 3. 跳过标题行
            if (rowIterator.hasNext()) rowIterator.next();

            List<OrderSetting> orderSettings = new ArrayList<>();

            // 4. 遍历数据行
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                // 日期单元格 (格式: yyyy-MM-dd)
                Cell dateCell = row.getCell(0);
                // 可预约人数单元格
                Cell numberCell = row.getCell(1);

                // 5. 解析数据
                Date orderDate;
                try {
                    orderDate = dateCell.getDateCellValue();
                } catch (Exception e) {
                    // 处理文本格式日期
                    throw new RuntimeException("日期格式错误");
                }

                int number = (int) numberCell.getNumericCellValue();

                // 6. 创建实体对象
                OrderSetting setting = new OrderSetting();
                setting.setOrderDate(orderDate);
                setting.setNumber(number);
                setting.setReservations(0); // 初始已预约人数为0

                orderSettings.add(setting);
            }

            // 7. 批量保存到数据库
            saveOrderSettings(orderSettings);

            // 8. 关闭资源
            workbook.close();
        }

// 批量保存方法
        private void saveOrderSettings(List<OrderSetting> settings) {
            for (OrderSetting setting : settings) {
                // 检查是否已存在该日期的记录
                OrderSetting existing = orderSettingMapper.findByOrderDate(setting.getOrderDate());

                if (existing != null) {
                    // 更新记录
                    existing.setNumber(setting.getNumber());
                    orderSettingMapper.update(existing);
                } else {
                    // 插入新记录
                    orderSettingMapper.insert(setting);
                }
            }
        }
    }



